package com.hx.vending.util;

import com.google.gson.Gson;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.processing.OperationManager;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.BatchStatus;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import com.qiniu.util.StringMap;
import com.qiniu.util.UrlSafeBase64;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PropertiesLoaderUtils;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

/**
 * Created by mccken on 2018/10/11 0011.
 */
public class QiniuyunClientUtil {

	//阿里云API的密钥Access Key ID
	@Value("${qiniuyun.accessKey}")
	private static String accessKey;
	//阿里云API的密钥Access Key Secret
	@Value("${qiniuyun.secretKey}")
	private static String secretKey;
	//阿里云API的bucket名称
	@Value("${qiniuyun.advertising.bucketName}")
	private static String bucket;
	@Value("${qiniuyun.advertising.url}")
	private static String url;
	@Value("${qiniuyun.transcoding.fops}")
	private static String fops;

	//构造一个带指定Zone对象的配置类 华南
	private static Configuration cfg = null;

	private static UploadManager uploadManager = null;
	private static BucketManager bucketManager = null;

	/**
	 * 对七牛空间中的文件进行持久化处理，适用于官方的fop指令和客户开发的ufop指令
	 * 例如图片处理指令，视频转码指令等
	 */
	private static OperationManager operationManager = null;

	//默认不指定key的情况下，以文件内容的hash值作为文件名
	private static Auth auth = null;
	private static String upToken = null;

	static {
		//获取properties中的值
		Resource resource = new ClassPathResource("Qiniuyun.properties");
		Properties props = null;
		try {
			props = PropertiesLoaderUtils.loadProperties(resource);
			accessKey = props.getProperty("qiniuyun.accessKey");
			secretKey = props.getProperty("qiniuyun.secretKey");
			bucket = props.getProperty("qiniuyun.advertising.bucketName");
			url = props.getProperty("qiniuyun.advertising.url");
			fops = props.getProperty("qiniuyun.transcoding.fops");

			cfg = new Configuration(Zone.zone2());
			auth = Auth.create(accessKey, secretKey);
			upToken = auth.uploadToken(bucket);

			uploadManager = new UploadManager(cfg);
			bucketManager = new BucketManager(auth, cfg);
			operationManager = new OperationManager(auth, cfg);

		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
	}

	/**
	 * 以流的方式上传视频到七牛云
	 */
	public static String uploadVideoToQiniuyunByStream(InputStream inputStream) throws Exception {

		// 上传文件key 
		String key = MD5.string2MD5(DateUtil.getTime());

		// 上传
		Response response = uploadManager.put(inputStream, key, upToken, null, null);
		
		//解析上传成功的结果
		DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);

		if (putRet.key == null) {

			return Constant.FAIL;
		}

		// 转码
		String newKey = transcodingVideoBy(key);

		// 转码后删除源文件
		String[] keys = {key};

		QiniuyunClientUtil.deleteVideoByKeyList(keys);

		return Constant.HTTP_STRTING + url + Constant.BACKSLASH_STRTING + newKey;
		
	}

	// 转码视频
	private static String transcodingVideoBy(String key) throws Exception{

		// 转码后的key 
		String newKey = MD5.string2MD5(DateUtil.getTime());

		//saveas接口 参数
		String saveAs = UrlSafeBase64.encodeToString(bucket + ":" + newKey);
		
		//处理命令 avthumb 和 saveas 通过管道符 |  进行连接
		String fops = "avthumb/mp4/vcodec/libx264|saveas/" + saveAs;

		StringMap putPolicy = new StringMap();
		putPolicy.put("persistentPipeline", "dm168");

		String persistentId = operationManager.pfop(bucket, key, fops, putPolicy);

		System.out.println("转码任务ID: " + persistentId);
		
		return newKey;
	}  

	// 批量删除视频
	public static void deleteVideoByKeyList(String[] keyList) throws Exception {

		BucketManager.BatchOperations batchOperations = new BucketManager.BatchOperations();
		batchOperations.addDeleteOp(bucket, keyList);
		Response response = bucketManager.batch(batchOperations);
		BatchStatus[] batchStatusList = response.jsonToObject(BatchStatus[].class);
		for (int i = 0; i < keyList.length; i++) {
			BatchStatus status = batchStatusList[i];
			String key = keyList[i];
			System.out.print(key + "\t");
			if (status.code == 200) {
				System.out.println("delete success");
			} else {
				System.out.println(status.data.error);
			}
		}
	}

	public static void main(String[] args) throws Exception {

//		List<String> l = new ArrayList<>();
//
//		String a = "9599b5e296d48c48ea4ec98ff86c94d1"; 
//		String a2 = "19fbe6e5015eba09a054d219f4f1decc";
//
//		l.add(a);
//		l.add(a2);
//		
//		//单次批量请求的文件数量不得超过1000
//		String[] keyList = l.toArray(new String[0]);
//		
//		BucketManager.BatchOperations batchOperations = new BucketManager.BatchOperations();
//		batchOperations.addDeleteOp(bucket, keyList);
//		Response response = bucketManager.batch(batchOperations);
//		BatchStatus[] batchStatusList = response.jsonToObject(BatchStatus[].class);
//		for (int i = 0; i < keyList.length; i++) {
//			BatchStatus status = batchStatusList[i];
//			String key = keyList[i];
//			System.out.print(key + "\t");
//			if (status.code == 200) {
//				System.out.println("delete success");
//			} else {
//				System.out.println(status.data.error);
//			}
//		}
		System.out.println(DateUtil.getTime());
		
		String s = uploadVideoToQiniuyunByStream(new FileInputStream(new File("C:\\Users\\mccken\\Desktop\\aa.avi")));

		System.out.println(DateUtil.getTime());
		
//		String s1 = uploadAdvertisingToQiniuyunByStream(new FileInputStream(new File("C:\\Users\\mccken\\Desktop\\test.mp4")));
//
		System.out.println(s);
//		System.out.println(s1);

	}

}
